﻿var AuditReasonSelectorVm = function() {
    var self = this;
    self.IsInitialized = ko.observable(false);
    self.AuditReasons = ko.observableArray([]);
    self.SelectedAuditReason = ko.observable();
    self.Show = ko.observable(false);
    self.Deferrer = null;

    self.Save = function() {
        if (self.SelectedAuditReason() == null) {
            alert("You must select a reason.");
            return;
        }
        self.Deferrer.resolve(self.SelectedAuditReason().Id());
        self.Close();
    };

    self.Cancel = function() {
        self.Deferrer.reject();
        self.Close();
        self.Deferrer = null;
    };

    self.Close = function() {
        self.Show(false);
        $.colorbox.close();
    };
    self.PromptUserForAuditReason = function() {
        self.Deferrer = $.Deferred();
        self.Show(true);
        self.ShowColorBox();
        return self.Deferrer;
    };
    self.ShowColorBox = function() {
        var height = $("#AuditReasonSelector").height();
        var colorBoxOptions = {
            href: "#AuditReasonSelector",
            inline: true,
            height: height,
            innerWidth: 300,
            minHeight: 100,
            maxHeight: $(window).height(),
            overlayClose: false,
            escKey: false,
            transition: "fade"
        };
        $.colorbox(colorBoxOptions);
    };
    self.GetAuditReasonsByAuditTypeId = function(auditTypeId) {
        $.ajax({
            url: "/Auditing/GetAuditReasonsByAuditTypeId",
            cache: false,
            data: { AuditTypeId: auditTypeId },
            dataType: "json",
            contentType: "application/json charset=utf-8",
            success: function(data) {
                self.AuditReasons.removeAll();;
                var parsedJson = JSON.parse(data);
                for (var i = 0; i < parsedJson.length; i++) {
                    var auditReasonVm = new AuditReasonVm(parsedJson[i]);
                    self.AuditReasons.push(auditReasonVm);;
                }
                self.IsInitialized(true);
            }
        });
    };

    $(document).bind('cbox_complete', function() {
        $.colorbox.resize();
    });
};